<template>
  <div class="feedback-widget">
    <!-- 反馈按钮 -->
    <el-button 
      class="feedback-trigger"
      type="primary"
      circle
      @click="showFeedback = true">
      <el-icon><ChatDotRound /></el-icon>
    </el-button>

    <!-- 反馈对话框 -->
    <el-dialog
      v-model="showFeedback"
      title="用户反馈"
      width="600px"
      :before-close="handleClose">
      
      <div class="feedback-content">
        <!-- 反馈类型选择 -->
        <div class="feedback-type">
          <h4>反馈类型</h4>
          <el-radio-group v-model="feedbackForm.type" class="type-options">
            <el-radio-button value="bug">
              <el-icon><Warning /></el-icon>
              错误报告
            </el-radio-button>
            <el-radio-button value="feature">
              <el-icon><Plus /></el-icon>
              功能建议
            </el-radio-button>
            <el-radio-button value="improvement">
              <el-icon><TrendCharts /></el-icon>
              改进建议
            </el-radio-button>
            <el-radio-button value="other">
              <el-icon><ChatDotRound /></el-icon>
              其他
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 满意度评分 -->
        <div class="satisfaction-rating">
          <h4>整体满意度</h4>
          <el-rate 
            v-model="feedbackForm.rating" 
            :max="5"
            show-text
            :texts="ratingTexts"
            :colors="ratingColors" />
        </div>

        <!-- 反馈内容 -->
        <div class="feedback-details">
          <h4>详细描述</h4>
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您遇到的问题或建议..."
            maxlength="1000"
            show-word-limit />
        </div>

        <!-- 联系方式 -->
        <div class="contact-info">
          <h4>联系方式 (可选)</h4>
          <el-input
            v-model="feedbackForm.contact"
            placeholder="邮箱或电话，方便我们联系您"
            maxlength="100" />
        </div>

        <!-- 截图上传 -->
        <div class="screenshot-upload">
          <h4>截图 (可选)</h4>
          <el-upload
            class="screenshot-uploader"
            :auto-upload="false"
            :on-change="handleScreenshotChange"
            :before-upload="beforeScreenshotUpload"
            accept="image/*"
            :limit="3"
            list-type="picture-card">
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">
                支持 JPG、PNG 格式，最多3张图片
              </div>
            </template>
          </el-upload>
        </div>

        <!-- 系统信息 -->
        <div class="system-info">
          <el-collapse>
            <el-collapse-item title="系统信息" name="system">
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">浏览器:</span>
                  <span class="value">{{ systemInfo.browser }}</span>
                </div>
                <div class="info-item">
                  <span class="label">操作系统:</span>
                  <span class="value">{{ systemInfo.os }}</span>
                </div>
                <div class="info-item">
                  <span class="label">屏幕分辨率:</span>
                  <span class="value">{{ systemInfo.screen }}</span>
                </div>
                <div class="info-item">
                  <span class="label">应用版本:</span>
                  <span class="value">{{ systemInfo.version }}</span>
                </div>
                <div class="info-item">
                  <span class="label">当前页面:</span>
                  <span class="value">{{ systemInfo.currentPage }}</span>
                </div>
                <div class="info-item">
                  <span class="label">时间戳:</span>
                  <span class="value">{{ systemInfo.timestamp }}</span>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="takeScreenshot">
            <el-icon><Camera /></el-icon>
            截图
          </el-button>
          <el-button 
            type="primary" 
            @click="submitFeedback"
            :loading="submitting">
            提交反馈
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 感谢对话框 -->
    <el-dialog
      v-model="showThanks"
      title="感谢您的反馈"
      width="400px"
      :show-close="false">
      
      <div class="thanks-content">
        <div class="thanks-icon">
          <el-icon size="64" color="#67C23A"><SuccessFilled /></el-icon>
        </div>
        <h3>反馈提交成功！</h3>
        <p>我们已收到您的反馈，将认真处理并持续改进产品体验。</p>
        <p v-if="feedbackId" class="feedback-id">
          反馈编号: {{ feedbackId }}
        </p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="showThanks = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useNotification } from '../../composables/useNotification'
import { APP_CONFIG } from '../../constants'
import { 
  ChatDotRound, 
  Warning, 
  Plus, 
  TrendCharts, 
  Camera, 
  SuccessFilled 
} from '@element-plus/icons-vue'

// 组合式函数
const route = useRoute()
const { success, error } = useNotification()

// 响应式数据
const showFeedback = ref(false)
const showThanks = ref(false)
const submitting = ref(false)
const feedbackId = ref('')

const feedbackForm = ref({
  type: 'bug',
  rating: 5,
  content: '',
  contact: '',
  screenshots: []
})

const ratingTexts = ['很差', '较差', '一般', '满意', '非常满意']
const ratingColors = ['#F56C6C', '#E6A23C', '#E6A23C', '#67C23A', '#67C23A']

// 系统信息
const systemInfo = ref({
  browser: '',
  os: '',
  screen: '',
  version: APP_CONFIG.version,
  currentPage: '',
  timestamp: ''
})

// 计算属性
const isFormValid = computed(() => {
  return feedbackForm.value.content.trim().length > 0
})

// 方法
const collectSystemInfo = () => {
  const userAgent = navigator.userAgent
  
  // 检测浏览器
  let browser = 'Unknown'
  if (userAgent.includes('Chrome')) browser = 'Chrome'
  else if (userAgent.includes('Firefox')) browser = 'Firefox'
  else if (userAgent.includes('Safari')) browser = 'Safari'
  else if (userAgent.includes('Edge')) browser = 'Edge'
  
  // 检测操作系统
  let os = 'Unknown'
  if (userAgent.includes('Windows')) os = 'Windows'
  else if (userAgent.includes('Mac')) os = 'macOS'
  else if (userAgent.includes('Linux')) os = 'Linux'
  else if (userAgent.includes('Android')) os = 'Android'
  else if (userAgent.includes('iOS')) os = 'iOS'
  
  systemInfo.value = {
    browser: `${browser} ${getBrowserVersion(userAgent)}`,
    os,
    screen: `${screen.width}x${screen.height}`,
    version: APP_CONFIG.version,
    currentPage: route.path,
    timestamp: new Date().toISOString()
  }
}

const getBrowserVersion = (userAgent) => {
  const match = userAgent.match(/(Chrome|Firefox|Safari|Edge)\/(\d+\.\d+)/)
  return match ? match[2] : ''
}

const handleScreenshotChange = (file) => {
  feedbackForm.value.screenshots.push(file)
}

const beforeScreenshotUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const takeScreenshot = async () => {
  try {
    if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: { mediaSource: 'screen' }
      })
      
      const video = document.createElement('video')
      video.srcObject = stream
      video.play()
      
      video.addEventListener('loadedmetadata', () => {
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(video, 0, 0)
        
        canvas.toBlob((blob) => {
          const file = new File([blob], 'screenshot.png', { type: 'image/png' })
          feedbackForm.value.screenshots.push(file)
          success('截图已添加')
        })
        
        stream.getTracks().forEach(track => track.stop())
      })
    } else {
      error('您的浏览器不支持截图功能')
    }
  } catch (err) {
    if (err.name !== 'NotAllowedError') {
      error('截图失败: ' + err.message)
    }
  }
}

const submitFeedback = async () => {
  if (!isFormValid.value) {
    error('请填写反馈内容')
    return
  }

  submitting.value = true

  try {
    // 构建反馈数据
    const feedbackData = {
      ...feedbackForm.value,
      systemInfo: systemInfo.value,
      timestamp: new Date().toISOString(),
      id: generateFeedbackId()
    }

    // 模拟提交到服务器
    await simulateSubmit(feedbackData)
    
    feedbackId.value = feedbackData.id
    showFeedback.value = false
    showThanks.value = true
    
    // 重置表单
    resetForm()
    
  } catch (err) {
    error('提交失败: ' + err.message)
  } finally {
    submitting.value = false
  }
}

const simulateSubmit = (data) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟网络请求
      if (Math.random() > 0.1) { // 90% 成功率
        console.log('反馈数据:', data)
        resolve()
      } else {
        reject(new Error('网络错误'))
      }
    }, 1000)
  })
}

const generateFeedbackId = () => {
  return `FB${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`
}

const resetForm = () => {
  feedbackForm.value = {
    type: 'bug',
    rating: 5,
    content: '',
    contact: '',
    screenshots: []
  }
}

const handleClose = () => {
  showFeedback.value = false
}

// 生命周期
onMounted(() => {
  collectSystemInfo()
})
</script>

<style scoped>
.feedback-widget {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 1000;
}

.feedback-trigger {
  width: 56px;
  height: 56px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.feedback-trigger:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.feedback-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feedback-type h4,
.satisfaction-rating h4,
.feedback-details h4,
.contact-info h4,
.screenshot-upload h4 {
  margin: 0 0 12px 0;
  color: var(--el-text-color-primary);
  font-size: 16px;
  font-weight: 600;
}

.type-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.type-options .el-radio-button {
  margin-right: 0;
}

.satisfaction-rating .el-rate {
  margin-top: 8px;
}

.screenshot-uploader {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.system-info {
  margin-top: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.value {
  color: var(--el-text-color-regular);
  text-align: right;
  word-break: break-all;
}

.thanks-content {
  text-align: center;
  padding: 24px 0;
}

.thanks-icon {
  margin-bottom: 16px;
}

.thanks-content h3 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
  font-size: 20px;
}

.thanks-content p {
  margin: 0 0 12px 0;
  color: var(--el-text-color-regular);
  line-height: 1.6;
}

.feedback-id {
  font-family: monospace;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .feedback-widget {
    bottom: 16px;
    right: 16px;
  }
  
  .feedback-trigger {
    width: 48px;
    height: 48px;
  }
  
  .type-options {
    flex-direction: column;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>



